package com.liangtian.mdm.system.mail.service.impl;

import com.liangtian.mdm.system.mail.model.Mail;
import com.liangtian.mdm.system.mail.service.MailService;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * <p>Encoding    :  UTF-8</p>
 * <p>Package Name: com.liangtian.mdm.system.mail.service.impl </p>
 * <p>Project Name: dm </p>
 * <p>Copyright   :  Copyright(c) 2016 石化盈科信息技术有限责任公司 </p>
 * <p>Created Time: 2016-05-26 10:25</p>
 * <p>Description : 邮件服务接口实现</p>
 *
 * @author : beamzhang
 * @version :  1.0
 */
//@Service
public class MailServiceImpl implements MailService {

    //日志打印对象
    private static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Value("${MAIL_SERVICE}")
    private String MAIL_SERVICE;
    @Value("${MAIL_FROM}")
    private String MAIL_FROM;
    @Value("${MAIL_SENDER}")
    private String MAIL_SENDER;
    @Value("${MAIL_PASSWORD}")
    private String MAIL_PASSWORD;
    @Value("${MAIL_CONTENTTYPE}")
    private String MAIL_CONTENTTYPE;
    @Value("${MAIL_SUBJECT}")
    private String MAIL_SUBJECT;
    @Value("${MAIL_SMTPPORT}")
    private String MAIL_SMTPPORT;
    @Value("${MAIL_SSLSMTPPORT}")
    private String MAIL_SSLSMTPPORT;

    /**
     * @param mail Mail 邮件对象事例
     * @desc 异步发送邮件
     */
    @Override
    public void sendMailAsyn(Mail mail) {
        final Mail mail2 = mail;
        Thread t = new Thread() {
            @Override
            public void run() {
                sendMail(mail2);
            }
        };
        t.start();
    }

    /**
     * @param mail Mail 邮件对象事例
     * @return boolean [true|false],如果发送成功返回true，否则返回false
     * @desc 同步发送邮件
     */
    @Override
    public boolean sendMail(Mail mail) {
        boolean result = true;

        if (null == mail.getMailServer()) {
            mail.setMailServer(MAIL_SERVICE);
        }
        if (null == mail.getFrom()) {
            mail.setFrom(MAIL_FROM);
        }
        if (null == mail.getContentType()) {
            mail.setContentType(MAIL_CONTENTTYPE);
        }
        if (null == mail.getSender()) {
            mail.setSender(MAIL_SENDER);
        }

        if (null == mail.getPassword()) {
            mail.setPassword(MAIL_PASSWORD);
        }

        if (null == mail.getSubject()) {
            mail.setSubject(MAIL_SUBJECT);
        }

        if (null == mail.getSmtpPort()) {
            mail.setSmtpPort(Integer.parseInt(MAIL_SMTPPORT));
        }

        SimpleEmail sm = new SimpleEmail();
        sm.setHostName(mail.getMailServer());
        sm.setSubject(mail.getSubject());
        sm.setContent(mail.getContent(), mail.getContentType());
        sm.setSslSmtpPort(mail.getSmtpPort() + "");
        if (mail.getPassword() != null) {
            sm.setAuthenticator(new DefaultAuthenticator(mail.getFrom(), mail.getPassword()));
        }
        try {
            sm.setFrom(mail.getFrom(), mail.getSender());
            String[] tos = mail.getTo().split("[,;]");
            for (String to : tos) {
                sm.addTo(to);
            }
            sm.send();
        } catch (EmailException ex) {
            result = false;
            logger.error("发送邮件异常:" + ex);
            ex.printStackTrace();
        }

        return result;
    }

    /**
     * @param to      String 邮件接收者
     * @param subject String 邮件标题
     * @param content String 邮件内容
     * @return boolean [true|false],如果发送成功返回true，否则返回false
     * @desc 邮件发送方法重构
     */
    @Override
    public boolean sendMail(String to, String subject, String content) {
        boolean result = false;
        Mail mail = new Mail();
        mail.setTo(to);
        mail.setSubject(subject);
        mail.setContent(content);
        result = sendMail(mail);
        return result;
    }

    /**
     * @param templateFile
     * @return String
     * @desc 根据模板文件获取文件内容
     */
    @Override
    public String getTemplateContentFromFile(String templateFile) {
        String result = "";
        InputStream is = MailServiceImpl.class.getClassLoader().getResourceAsStream("email/" + templateFile + ".html");
        InputStreamReader isr;
        try {
            isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String s;
            while ((s = br.readLine()) != null) {
                result += s;
            }
            br.close();

        } catch (IOException ex) {
            logger.error("获取邮件模板异常");
            ex.printStackTrace();
        }
        return result;
    }
}
